package net.wy.commons.util;

import org.springframework.web.util.HtmlUtils;

import java.util.regex.Pattern;

public class TextUtil {
	public static String toHtml(String str) {
		return str.replaceAll("\n", "<br/>");	
	}

    /**
     * 去掉字符串中的html标记
     *
     * @param s           源字符串
     * @param replacement
     * @return
     */
    public static String cleanHTML(String s, String replacement) {
        if (s == null) {
            return s;
        }
        if (replacement == null) {
            replacement = "";
        }
        String html = new String(s);
        String[] htmlTag = {""};
        String regex = "";

        html = Pattern.compile("<!--((?!<!--).)*-->", Pattern.DOTALL).matcher(html).replaceAll(replacement);
        html = Pattern.compile("<script((?!</script).)*</script>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE).matcher(html).replaceAll(replacement);
        html = Pattern.compile("<style((?!</style).)*</style>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE).matcher(html).replaceAll(replacement);

        for (int i = 0; i < htmlTag.length; i++) {
            regex = "<" + htmlTag[i] + "[^<]*>";
            html = Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(html).replaceAll(replacement);
            regex = "</" + htmlTag[i] + ">";
            html = Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(html).replaceAll(replacement);
        }
        //html = html.replaceAll("\\s+", replacement);
        html = html.replaceAll("&nbsp;", " ");
        html = html.replaceAll("\r\n", "");
        html = html.replaceAll("\n", "");
        html = HtmlUtils.htmlEscape(html);
        html = HtmlUtils.htmlUnescape(html);
        return html;
    }
}
